<?php
namespace app\middleware;

use Closure;
use app\service\JwtService;

class CheckAuthMiddleware
{
    public function handle($request, Closure $next)
    {
        $authHeader = $request->header('Authorization');
        if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问'], 401);
        }

        $token = $matches[1];
        $payload = JwtService::verifyToken($token);
        if (!$payload) {
            return json(['code' => 401, 'msg' => '无效或过期的Token'], 401);
        }

        $request->user = $payload; // 统一字段名，方便下游使用

        return $next($request);
    }
}

